package com.kosam.commons.base.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider;
import com.kosam.commons.base.exception.BusinessException;
import com.kosam.commons.base.exception.InternalServerException;
import com.kosam.commons.base.serializer.CustomNullJsonSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by tgx on 2017/2/20.
 */
public class JsonUtils {
    private static Logger log = LoggerFactory.getLogger(JsonUtils.class);

    static ObjectMapper objectMapper;

    private JsonUtils() {
    }

    /**
     * @param content   source JSON value
     * @param valueType Java Bean Type
     * @param <T>
     * @return
     * @throws BusinessException
     */
    public static <T> T readValue(String content, Class<T> valueType) throws BusinessException {
        if (objectMapper == null) {
            objectMapper = new ObjectMapper();

            DefaultSerializerProvider sp = new DefaultSerializerProvider.Impl();
            sp.setNullValueSerializer(new CustomNullJsonSerializer());
            objectMapper.setSerializerProvider(sp);
        }

        try {
            return objectMapper.readValue(content, valueType);
        } catch (Exception e) {
            log.error(e.getMessage(), e);

            String detail = "Error happens when convert json to object by jackson.";
            throw new InternalServerException(detail);
        }
    }

    /**
     * @param object
     * @return
     * @throws BusinessException
     */
    public static String toJSon(Object object) throws BusinessException {
        if (objectMapper == null) {
            objectMapper = new ObjectMapper();

            DefaultSerializerProvider sp = new DefaultSerializerProvider.Impl();
            sp.setNullValueSerializer(new CustomNullJsonSerializer());
            objectMapper.setSerializerProvider(sp);
        }

        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            log.error(e.getMessage(), e);

            String detail = "Error happens when convert object to json by jackson.";
            throw new InternalServerException(detail);
        }
    }
}
